package org.wk.news.api.controller;

import com.alibaba.druid.support.json.JSONUtils;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.MediaType;
import org.springframework.stereotype.Controller;
import org.springframework.ui.ModelMap;
import org.springframework.web.bind.annotation.*;
import org.wk.core.common.view.ResponseVo;
import org.wk.news.service.NewsManageService;
import org.wk.news.service.NewsPraiseService;
import org.wk.news.view.NewsManageVo;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.List;
import java.net.URL;
import java.net.URLConnection;
import java.util.Map;

@Controller
public class WxController {

    private final Logger logger = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private NewsManageService manageService;
    @Autowired
    private NewsPraiseService newsPraiseService;


    @RequestMapping(value="/loginRes",method=RequestMethod.GET)
    @ResponseBody
    public JSON findNews(@RequestParam(required = false) String code){
        logger.info("获取微信授权>>>>{}");
        //https://api.weixin.qq.com/sns/jscode2session?appid=APPID&secret=SECRET&js_code=JSCODE&grant_type=authorization_code
        //请求
        String str = sendGet("https://api.weixin.qq.com/sns/jscode2session","appid=wx3676636d5e06537d&secret=56561b7f812d5f14b767926e34bfc978&js_code="+code+"&grant_type=authorization_code");
        System.out.println(str);
        Object parse = JSONUtils.parse(str);
        Map<String, String> map = (Map<String, String>) parse;
        JSON json = JSON.parseObject(str);
        /* String openid = map.get("openid");
        String sessionkey = map.get("session_key");
       String api = "https://api.weixin.qq.com/sns/userinfo?access_token=" + sessionkey + "&openid=" + openid
                + "&lang=zh_CN";
        str = sendGet("https://api.weixin.qq.com/sns/userinfo","access_token=" + sessionkey + "&openid=" + openid+ "&lang=zh_CN");
        parse = JSONUtils.parse(str);
        map = (Map<String, String>)parse;
        String nickname = map.get("nickname");
        String unionid = map.get("unionid");
        String icon = map.get("headimgurl");
        System.out.println(icon);
        map = new HashMap<>();
        map.put("username", nickname);
        map.put("unionid", unionid);
        map.put("url", icon);*/

        ResponseVo result = new ResponseVo();
        result.setData(map);
        logger.info("获取微信授权>>>>{}",result);
        return json;
    }

    public static void main(String[] args) {

    }

    /**
     * 向指定URL发送GET方法的请求
     *
     * @param url
     *            发送请求的URL
     * @param param
     *            请求参数，请求参数应该是 name1=value1&name2=value2 的形式。
     * @return URL 所代表远程资源的响应结果
     */
    public static String sendGet(String url, String param) {
        String result = "";
        BufferedReader in = null;
        try {
            String urlNameString = url + "?" + param;
            URL realUrl = new URL(urlNameString);
            // 打开和URL之间的连接
            URLConnection connection = realUrl.openConnection();
            // 设置通用的请求属性
            connection.setRequestProperty("accept", "*/*");
            connection.setRequestProperty("connection", "Keep-Alive");
            connection.setRequestProperty("user-agent",
                    "Mozilla/4.0 (compatible; MSIE 6.0; Windows NT 5.1;SV1)");
            // 建立实际的连接
            connection.connect();
            // 获取所有响应头字段
            Map<String, List<String>> map = connection.getHeaderFields();
            // 遍历所有的响应头字段
            for (String key : map.keySet()) {
                System.out.println(key + "--->" + map.get(key));
            }
            // 定义 BufferedReader输入流来读取URL的响应
            in = new BufferedReader(new InputStreamReader(
                    connection.getInputStream()));
            String line;
            while ((line = in.readLine()) != null) {
                result += line;
            }
        } catch (Exception e) {
            System.out.println("发送GET请求出现异常！" + e);
            e.printStackTrace();
        }
        // 使用finally块来关闭输入流
        finally {
            try {
                if (in != null) {
                    in.close();
                }
            } catch (Exception e2) {
                e2.printStackTrace();
            }
        }
        return result;
    }

   /* *//**
     * @Description 获取新闻详情
     * @Param [newsId] 新闻ID
     * @author ZhaoPing'an
     * @Date 2018/6/9 13:56
     *//*
    @RequestMapping(value="/news/{news_id}",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
    public String findNewsInfo(@PathVariable("news_id") String newsId, @RequestParam(value = "userId", required = false) String userId ,ModelMap modelMap){
        logger.info("获取新闻资讯详细信息>>>>{}");
        NewsManageVo newsManageVo = manageService.findNewsInfo(newsId);

        modelMap.put("news", newsManageVo);
        modelMap.put("userId", userId);
        if (userId==null) {
            modelMap.put("praiseStatus",false);
        } else {
            modelMap.put("praiseStatus",newsPraiseService.selectPraise(userId,newsId));
        }
        logger.info("获取新闻资讯详细信息>>>>{}",JSONObject.toJSONString(newsManageVo));
        return "news/detail";
    }

    *//**
     * @description 获取资讯分享详情
     * @param
     * @author ZhaoPing'an
     * @date 2018/6/9 14:03
     *//*
    @ResponseBody
    @RequestMapping(value="/news/{news_id}/share_info",method=RequestMethod.GET,produces=MediaType.APPLICATION_JSON_UTF8_VALUE)
    public ResponseVo findNewsShareInfo(@PathVariable("news_id") String newsId){
        logger.info("获取新闻资讯分享信息>>>>{}");
        ResponseVo responseVo = manageService.findShareInfoByNewsId(newsId);
        logger.info("获取新闻资讯分享信息>>>>{}",responseVo);
        return responseVo;
    }*/
}
